package com.chen.schedule.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String[] split = requestURI.split("/");
        String methodName = split[split.length - 1];
        // 约定：方法名与请求路径的最后一部分一致
        // 使用反射的原因：根据截取的方法名来调用具体的方法
        Class<? extends BaseController> aClass = this.getClass();
        try {
            // 获取方法
            Method method = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //  强制访问
            method.setAccessible(true);
            //  调用方法 参数： 一：那个类调用 ， 参数二调用这个方法需要的参数
            method.invoke(this, req, resp);
        } catch (Exception e) {
            resp.setStatus(404);
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
